import { FC, Ref, forwardRef, useState, useImperativeHandle } from "react";
import { Modal, Tree } from "antd";
import { menuRoutes } from "@/router";
import { updateAdmin } from "@/api/user";

interface IProps {
  ref: Ref<{}>;
  onOk: () => void;
}

let curUserInfo: any = {};

const UserMenuModal: FC<IProps> = forwardRef(({ onOk }, ref) => {
  // !! curUserInfo 放在这不行，我们使用它主要是为了做一份临时储存。放在这儿的话，当该组件的 更新时，curUserInfo 被重新创建了。
  // let curUserInfo = {};
  const [open, setOpen] = useState(false);
  const [checkedKeys, setCheckedKeys] = useState([]);

  const handleOk = () => {
    // 调用接口修改当前管理员信息
    updateAdmin(
      curUserInfo.adminname,
      curUserInfo.password,
      curUserInfo.role,
      checkedKeys
    );
    setOpen(false);
    // 调用父组件传递过来的 onOk
    onOk();
  };

  const handleCancel = () => {
    setOpen(false);
    // TODO...
  };

  // Tree check 事件
  const onCheck = (keys: any) => {
    setCheckedKeys(keys);
  };

  // 通过 useImperativeHandle 定义该组件对外暴露的数据或方法
  useImperativeHandle(ref, () => {
    return {
      openModal(obj: any) {
        // console.log("obj", obj);
        // 将父组件传递的当前操作的用户信息obj存在 curUserInfo 中
        curUserInfo = obj;
        setCheckedKeys(obj.checkedKeys);
        setOpen(true);
      },
    };
  });

  return (
    <Modal title="分配权限" open={open} onOk={handleOk} onCancel={handleCancel}>
      <Tree
        checkable
        defaultExpandAll
        fieldNames={{ title: "label" }}
        treeData={menuRoutes}
        checkedKeys={checkedKeys}
        onCheck={onCheck}
      />
    </Modal>
  );
});

export default UserMenuModal;
